package com.lagace.spark.twitter;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.Workspace;
import org.jivesoftware.spark.component.tabbedPane.SparkTabbedPane;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.preference.PreferenceManager;

import winterwell.jtwitter.Twitter;

import com.lagace.spark.twitter.local.LocalTwitterPreferences;
import com.lagace.spark.twitter.local.TwitterSettingsManager;

public class TwitterPlugin implements Plugin {
	private LocalTwitterPreferences localPrefs;
	private TwitterPreferences twitterPreferences;
	private Twitter t;
	private Thread thread;
	private TwitterTimelinePane timelinePane;
	private TweetPanel tweetPanel; 

	public TwitterPlugin() {
		loadTwitterPreferences();
		initTwitterConnection();
	}

	private void loadTwitterPreferences() {
		localPrefs = TwitterSettingsManager.getLocalTwitterPreferences();
		twitterPreferences = new TwitterPreferences();
	}

	private void initTwitterConnection() {
		if(hasPreferencesConfigured()){
			t = new Twitter(localPrefs.getUsername(), localPrefs.getPassword());
			timelinePane = new TwitterTimelinePane(t, getRefreshTime());
			tweetPanel = new TweetPanel(t);
		}
	}

	public void initialize() {
		addPreference();
		addTabToSpark();
	}

	private boolean hasPreferencesConfigured() {
		return TwitterUtil.isNotBlank(localPrefs.getUsername()) && TwitterUtil.isNotBlank(localPrefs.getPassword());
	}

	public void shutdown() {
		timelinePane.shutDown();
	}

	public boolean canShutDown() {
		return false;
	}

	public void uninstall() { /*no resources are created for this plugin*/ }

    private void addPreference(){
        PreferenceManager preferenceManager = SparkManager.getPreferenceManager();
		preferenceManager.addPreference(twitterPreferences);
     }
	
    private void addTabToSpark(){
        Workspace workspace = SparkManager.getWorkspace();
        SparkTabbedPane tabbedPane = workspace.getWorkspacePane();
    	tabbedPane.addTab("Twitter", null, createTwitterTabUI());
    	if(hasPreferencesConfigured())			
			startTimelinePaneDaemon();
    }
    
    public void reloadPlugin() {
    	loadTwitterPreferences();
		initTwitterConnection();
        Workspace workspace = SparkManager.getWorkspace();
        SparkTabbedPane tabbedPane = workspace.getWorkspacePane();
        tabbedPane.removeTabAt(tabbedPane.indexOfTab("Twitter"));
        tabbedPane.validate();
        addTabToSpark();
        tabbedPane.validate();
        tabbedPane.setSelectedTab(tabbedPane.getTabAt(tabbedPane.indexOfTab("Twitter")));
	}

	private JPanel createTwitterTabUI() {
		GridBagLayout gbl = new GridBagLayout();
		GridBagConstraints gbc = new GridBagConstraints();

		JPanel twitterTabPanel = new JPanel();
		
		if(hasPreferencesConfigured()){
			setTimelinePaneConstraints(gbl, gbc);
			setTweetPanelConstraints(gbl, gbc);
			
			twitterTabPanel.setLayout(gbl);
		    twitterTabPanel.add(timelinePane);
		    twitterTabPanel.add(tweetPanel);
		}else{
			final JButton b = new JButton("Save");
			b.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent e) {
						if (e.getSource() == b)
							twitterPreferences.commit();
					}
				}
			);
			twitterTabPanel.add(twitterPreferences.getUI());
			gbc.gridx = 1;
			gbc.gridy = 1;
			twitterTabPanel.add(b);
		}
		return twitterTabPanel;
	}

	private void setTweetPanelConstraints(GridBagLayout gbl, GridBagConstraints gbc) {
			configureTweetPanelConstraints(gbc);
			gbl.setConstraints(tweetPanel, gbc);
	}

	private void setTimelinePaneConstraints(GridBagLayout gbl, GridBagConstraints gbc) {
		configureTimelinePaneContsraints(gbc);
		gbl.setConstraints(timelinePane, gbc);
	}

	int getRefreshTime() {
		if(isValidRefreshTime(localPrefs.getRefreshTime()))
			return 2; //yeah, i'll make two minute refresh default
		else
			return Integer.parseInt(localPrefs.getRefreshTime());
	}

	boolean isValidRefreshTime(String refreshTime) {
		return null == refreshTime || refreshTime.length() <= 0;
	}
	
	void configureTweetPanelConstraints(GridBagConstraints gbc) {
		gbc.gridx = 0;
		gbc.gridy = 1;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.weightx = 1; 
		gbc.weighty = 1; 
		gbc.fill = GridBagConstraints.BOTH; 
		gbc.anchor = GridBagConstraints.PAGE_END;
	}

	void configureTimelinePaneContsraints(GridBagConstraints gbc) {
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.gridwidth = 1;
		gbc.gridheight = 1;
		gbc.weightx = 1; 
		gbc.weighty = 100; 
		gbc.fill = GridBagConstraints.BOTH; 
		gbc.anchor = GridBagConstraints.CENTER;
	}
    
	void startTimelinePaneDaemon() {
		thread = new Thread(timelinePane);
        thread.start();
	}
}
